﻿Imports System.Data.SqlClient
Imports System.Data

Public Class Config
    Dim selectedindex As Integer
    Dim query As String
    'BindingSource
    Public WithEvents bs As New BindingSource
    ' Adaptador de datos sql
    Private SqlDataAdapter As SqlDataAdapter
    ' Cadena de conexión
    Private Const cs As String = "Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01"
    ' flag
    Private bEdit As Boolean

    Private Sub Config_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With DataGridView1
            ' alternar color de filas
            .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite
            .DefaultCellStyle.BackColor = Color.Beige
            ' Establecer el origen de datos para el DataGridview
            .DataSource = bs
        End With
        LoadAll()
    End Sub

    Public Sub LoadAll()
        If CheckBox1.Checked = False Then
            cbxprofiles.Enabled = False
            DataGridView1.Enabled = False
        End If
        Label9.ForeColor = My.Settings.textcolor
        Label9.BackColor = My.Settings.textbackcolor
        piclogo.ImageLocation = "http://143.116.204.27/SFDCADMIN/LOGOS/" + My.Settings.logo
        'Llenamos todos los combo box con la funcion FillComboBox(objeto a llenar ,consulta, campo del resultado a usar como visible)
        FillComboBox(cbxprofiles, "Select * from Perfiles order by nombre", 1)
        FillComboBox(cbxlogos, "Select RTRIM(logoname) as logoname from Logos order by logoname", 0)
        FillComboBox(cbxsfdcpcs, "Select referencia from Autosfdc_ip order by referencia", 0)
    End Sub

    Public Sub FillComboBox(ByVal component As Object, ByVal query As String, ByVal arraynumber As Integer)
        Dim cnn As New SqlConnection("Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01")
        Dim cmd As New SqlCommand(query, cnn)
        Dim reader As SqlDataReader
        Using cnn
            cnn.Open()
            reader = cmd.ExecuteReader
            component.Items.Clear()
            While reader.Read
                component.Items.Add(reader(arraynumber)).ToString.Trim()
            End While
            reader.Close()
        End Using
    End Sub

    Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click
        Me.Close()
    End Sub

    Private Sub cbxprofiles_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxprofiles.SelectedIndexChanged
        Dim cnn As New SqlConnection("Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01")
        Dim cmd As New SqlCommand("Select id_perfil from perfiles where nombre = '" + cbxprofiles.SelectedItem.ToString.Trim + "'", cnn)
        lblselectedprofile.Text = cbxprofiles.SelectedItem.ToString.Trim
        selectedindex = cbxprofiles.SelectedIndex
        Dim id As Integer

        Using cnn
            cnn.Open()
            id = cmd.ExecuteScalar
            cnn.Close()
        End Using

        'Dim da As New SqlDataAdapter("SELECT     Emu_Configs.device as Unit, Emu_Configs.nombre as Name, Emu_Configs.ip  as SFDCIP FROM         Emu_Configs INNER JOIN                      Perfiles ON Emu_Configs.id_perfil = Perfiles.id_perfil WHERE     (Perfiles.nombre = '" + cbxprofiles.SelectedItem.ToString.Trim + "') order by Emu_Configs.nombre", cnn)
        'Dim ds As New DataSet
        'da.Fill(ds)
        'DataGridView1.DataSource = ds.Tables(0)

        query = "SELECT     id_config, nombre,ip, device FROM Emu_Configs WHERE     (id_perfil = " & id & ")"
        cargar_registros(query, DataGridView1)
        DataGridView1.Columns(0).Visible = False
    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then
            My.Settings.custom = True
            MainForm.cbxunits.Enabled = True
            gbunit.Enabled = False
            cbxprofiles.Enabled = True
            DataGridView1.Enabled = True
            MainForm.ToolStripStatusLabel5.Visible = True
            MainForm.lblprofile.Visible = True
        Else
            My.Settings.custom = False
            MainForm.cbxunits.Enabled = False
            gbunit.Enabled = True
            cbxprofiles.Enabled = False
            DataGridView1.Enabled = False
            MainForm.ToolStripStatusLabel5.Visible = False
            MainForm.lblprofile.Visible = False
        End If
    End Sub

    Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
        Actualizar()
        My.Settings.unit = Return_Unit(txtunit.Text.Trim)
        MainForm.lbldevice.Text = My.Settings.unit
        My.Settings.sfdcip = txtsfdcip.Text.Trim
        MainForm.lblsfdcip.Text = My.Settings.sfdcip
        My.Settings.port = txtport.Text.Trim
        If CheckBox1.Checked = True Then
            If selectedindex <> -1 Then
                cbxprofiles.SelectedIndex = selectedindex
                Asignar_Perfil()
                My.Settings.Save()
                Me.Close()
            Else
                MsgBox("Please, select a valid profile or disable custom profile option!", MsgBoxStyle.Critical, "Error!")
            End If
        Else
            MainForm.lblsfdcip.Text = My.Settings.sfdcip
            MainForm.lbldevice.Text = My.Settings.unit
            My.Settings.Save()
            Me.Close()
        End If

    End Sub

    Public Sub Load_Settings() Handles Me.Load
        If My.Settings.custom = True Then
            CheckBox1.Checked = True
            gbunit.Enabled = False
        Else
            CheckBox1.Checked = False
            gbunit.Enabled = True
        End If
        txtport.Text = My.Settings.port
        txtsfdcip.Text = My.Settings.sfdcip
        txtunit.Text = My.Settings.unit
        cbxprofiles.SelectedText = My.Settings.profilename
        Label9.ForeColor = My.Settings.textcolor
        MainForm.TextBox1.BackColor = My.Settings.textbackcolor
    End Sub

    Private Sub Asignar_Perfil()
        Dim cnn As New SqlConnection("Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01")
        Dim cmd As New SqlCommand("SELECT     Emu_Configs.nombre FROM         Emu_Configs INNER JOIN                      Perfiles ON Emu_Configs.id_perfil = Perfiles.id_perfil WHERE     (Perfiles.nombre = @name) order by Emu_Configs.nombre", cnn)
        My.Settings.profilename = cbxprofiles.SelectedItem.ToString.Trim
        cmd.Parameters.AddWithValue("@name", My.Settings.profilename.ToString.Trim)
        Dim reader As SqlDataReader
        Using cnn
            cnn.Open()
            reader = cmd.ExecuteReader
            MainForm.cbxunits.Items.Clear()
            MainForm.cbxunits.SelectedIndex = -1
            MainForm.cbxunits.Text = ""
            MainForm.lblprofile.Text = My.Settings.profilename
            While reader.Read
                MainForm.cbxunits.Items.Add(reader(0).ToString.Trim)
            End While
            reader.Close()
        End Using
        'MsgBox("El perfil " + My.Settings.profilename + " se ha asignado correctamente!", MsgBoxStyle.OkOnly, "Done!")
    End Sub

    Private Sub cbxlogos_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxlogos.SelectedIndexChanged
        piclogo.ImageLocation = "http://143.116.204.27/SFDCADMIN/LOGOS/" + cbxlogos.SelectedItem.ToString.Trim
        My.Settings.logo = cbxlogos.SelectedItem.ToString.Trim
        MainForm.piclogomain.ImageLocation = "http://143.116.204.27/SFDCADMIN/LOGOS/" + cbxlogos.SelectedItem.ToString.Trim
    End Sub

    Private Sub cbxsfdcpcs_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxsfdcpcs.SelectedIndexChanged
        Dim cnn As New SqlConnection("Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01")
        Dim cmd As New SqlCommand("Select autosfdc from autosfdc_ip where (referencia = @nombre)", cnn)
        cmd.Parameters.AddWithValue("@nombre", cbxsfdcpcs.SelectedItem.ToString.Trim)
        cnn.Open()
        txtsfdcip.Text = cmd.ExecuteScalar
        cnn.Close()
    End Sub

    Public Function Return_Unit(ByVal unit As String) As String
        Dim tam As Integer = unit.Length
        If tam = 1 Then
            Return "00" + unit
        ElseIf tam = 2 Then
            Return "0" + unit
        Else
            Return unit
        End If
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        cdiag.ShowDialog()
        My.Settings.textcolor = cdiag.Color
        Label9.ForeColor = My.Settings.textcolor
        MainForm.TextBox1.ForeColor = My.Settings.textcolor
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        cdiag.ShowDialog()
        My.Settings.textbackcolor = cdiag.Color
        Label9.BackColor = My.Settings.textbackcolor
        MainForm.TextBox1.BackColor = My.Settings.textbackcolor
    End Sub

    'Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    'If bEdit Then
    'preguntar si se desea guardar
    'If (MsgBox("Save changes?", MsgBoxStyle.YesNo, "Save")) = MsgBoxResult.Yes Then
    'Actualizar(False)
    'End If
    'End If
    'End Sub

    Public Sub Actualizar(Optional ByVal bCargar As Boolean = True)
        ' Actualizar y guardar cambios
        If Not bs.DataSource Is Nothing Then
            Try
                SqlDataAdapter.Update(CType(bs.DataSource, DataTable))
                If bCargar Then
                    cargar_registros(query, DataGridView1)
                End If
                FillComboBox(cbxprofiles, "Select * from Perfiles order by nombre", 1)
                'cbxprofiles.SelectedText = lblselectedprofile.Text
            Catch ex As DBConcurrencyException
                MsgBox("Please select a valid profile!", MsgBoxStyle.Critical, "Error!")
            End Try
            DataGridView1.Columns(0).Visible = False
        End If
    End Sub

    Private Sub cargar_registros(ByVal sql As String, ByVal dv As DataGridView)
        Try
            ' Inicializar el SqlDataAdapter indicandole el comando y el connection string
            SqlDataAdapter = New SqlDataAdapter(sql, cs)

            Dim SqlCommandBuilder As New SqlCommandBuilder(SqlDataAdapter)

            ' llenar el DataTable
            Dim dt As New DataTable()
            SqlDataAdapter.Fill(dt)

            ' Enlazar el BindingSource con el datatable anterior
            ' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            bs.DataSource = dt

            With dv
                .Refresh()
                ' coloca el registro arriba de todo
                .FirstDisplayedScrollingRowIndex = bs.Position
            End With

            bEdit = False

        Catch exSql As SqlException
            MsgBox(exSql.Message.ToString)
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        bEdit = True
    End Sub

    Private Sub Button9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click
        EditProfile.ShowDialog()
    End Sub

    Private Sub btn_update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update.Click
        Actualizar()
    End Sub

    Private Sub btn_delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_delete.Click

        If DataGridView1.RowCount > 1 Then
            If Not bs.Current Is Nothing Then
                If MsgBox("Do you want to permanently delete this record?", MsgBoxStyle.OkCancel, "Alert!") = MsgBoxResult.Ok Then
                    ' eliminar
                    bs.RemoveCurrent()
                    'Guardar los cambios y recargar
                    Actualizar()
                End If
            Else
                MsgBox("There is no current record to delete!", MsgBoxStyle.Exclamation, "Error!")
            End If
        Else
            MsgBox("You can't delete this record, the profile must have at least one unit!", MsgBoxStyle.Exclamation, "Error!")
        End If


    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        If lblselectedprofile.Text.Trim <> "" Then
            AddUnit.ShowDialog()
        Else
            MsgBox("Please, select a valid profile to add new units!", MsgBoxStyle.Critical, "Error!")
        End If
    End Sub

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
        cdiag.ShowDialog()
        My.Settings.backcolor = cdiag.Color
        MainForm.MyColour = My.Settings.backcolor
        Button8.ForeColor = My.Settings.backcolor
        MainForm.BackColor = My.Settings.backcolor
    End Sub
End Class